package com.zs.demo.shiro.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/* @Desc: jwt工具类
 * @author:zhengs  
 * @Time: 2018/11/23 14:39
 * @Copyright: © zhengs 版权所有  
 * @Warning: 本内容仅限于本公司内部传阅,禁止外泄或用于其它商业目的  
 */
public class JwtUtil {

    private static final long EXPIRE_TIME = 1*60*1000;

    /* @Desc: 生成加密的token
     * @author:zhengs
     * @Time: 2018/11/23 14:35
     * @param uid 用户ID
     * @param username 用户名
     * @param secret 用户密码（秘钥）
     * @return 加密token
     */
    public static String createToken(String uid, String username, String secret) {
        try {
            Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            return JWT.create()
                    .withClaim("uid", uid)
                    .withClaim("username", username)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /* @Desc: 验证token是否合法
     * @author:zhengs
     * @Time: 2018/11/23 14:38
     * @param token 待验证token
     * @param username 用户名
     * @param secret 用户密码(秘钥)
     * @return
     */
    public static boolean verifyToken(String token, String username, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /* @Desc: 根据token获取用户名
     * @author:zhengs
     * @Time: 2018/11/23 14:37
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}
